// 同时发送异步代码的次数
let ajaxTimes=0;

export const request=(params)=>{
    //判断url中是否带有/my/，若有则在header中带上token
    let header={...params.header};
    if(params.url.includes('/my/')){
      // 拼接header带上token
      header['Authorization']=wx.getStorageSync('token')
    }

    ajaxTimes++;
    // 显示加载效果啊
    wx.showLoading({
      title: '加载中',
      mask: true
    });

    // 定义公共URL
    const baseUrl="https://api-hmugo-web.itheima.net/api/public/v1";
    return new Promise((resolve,reject)=>{
        wx.request({
          ...params,
          header:header,
          url:baseUrl+params.url,
          success:(result)=>{
              resolve(result.data.message);
          },
          fail:(err)=>{
              reject(err);
          },
          complete:()=>{
              ajaxTimes--;
              if(ajaxTimes===0){
                // 关闭加载效果
                wx.hideLoading();
              }
          }
        })
    })
}

export const showModal=({content})=>{
  return new Promise((resolve,reject)=>{
    wx.showModal({
      content: content,
      title: '提示',
      success: (res) => {
        resolve(res);
      },
      fail:(err)=>{
        reject(err);
      }
    })
  })
}

export const showToast=({title})=>{
  return new Promise((resolve,reject)=>{
    wx.showToast({
      title: title,
      icon: 'none',
      success: (res) => {
        resolve(res);
      },
      fail:(err)=>{
        reject(err);
      }
    })
  })
}

export const getUserProfile=({desc})=>{
  return new Promise((resolve,reject)=>{
    wx.getUserProfile({
      desc: desc,
      success: (res) => {
        resolve(res);
      },
      fail:(err)=>{
        reject(err);
      }
    })
  })
}

export const login=()=>{
  return new Promise((resolve,reject)=>{
    wx.login({
      timeout: 10000,
      success: (res) => {
        resolve(res);
      },
      fail:(err)=>{
        reject(err);
      }
    })
  })
}

export const requestPayment=(pay)=>{
  return new Promise((resolve,reject)=>{
    wx.requestPayment({
      ...pay,
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        reject(err);
      },
    })
  })
}